package cn.shenshen.shop.web.advice;

import cn.shenshen.shop.util.BusinessException;
import cn.shenshen.shop.util.CodeMsg;
import cn.shenshen.shop.util.MemberCodeMsg;
import cn.shenshen.shop.util.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


@ControllerAdvice
public class CommonExceptionAdvice {

    //处理自定义异常
    @ExceptionHandler(BusinessException.class)
    @ResponseBody//不贴则会去找对应的视图
    public Result handException(BusinessException e){
        CodeMsg codeMsg = e.getCodeMsg();
        return Result.error(codeMsg);
    }

    //处理参数绑定异常
    @ExceptionHandler(BindException.class)
    @ResponseBody//不贴则会去找对应的视图
    public Result handBindException(BindException e){
        System.out.println(e.getMessage());
        //获取错误信息
        ObjectError objectError = e.getAllErrors().get(0);
        String errorMsg = objectError.getDefaultMessage();
        //封装到对应的codemsg中
        MemberCodeMsg codeMsg = MemberCodeMsg.fillArgs(errorMsg);
        return Result.error(codeMsg);
    }

    //系统默认异常处理
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handException(Exception e){
        return Result.defaultError();
    }

}
